package leetcode;

import java.util.Arrays;

public class Code5 {
    public int kthLargestElement(int k, int[] nums) {
        k = k - 1;
        int index = 0;
        int a = 0;
        int b = nums.length - 1;
        while (true) {
            int start = a;
            int end = b;
            index = nums[start];
            while (start != end) {
                while (nums[end] < index && start != end) {
                    end--;
                }
                if (start != end) {
                    nums[start] = nums[end];
                    start++;
                }
                while (nums[start] > index && start != end) {
                    start++;
                }
                if (start != end) {
                    nums[end] = nums[start];
                    end--;
                }
            }
            nums[start] = index;
            if (start > k) {
                b = start - 1;
            } else if (start < k) {
                a = start + 1;
            } else {
                return nums[start];
            }
        }
    }
}
